package com.dianshang.elasticsearch;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.HashMap;
import java.util.Map;

/**
 * 搜索引擎(ElasticSearch)
 */
public class ElasticSearch2Demo {

    /**
     * 新增和修改数据：
     *      新增一条/多条数据到bulk
     *      如果ID不存在则新增,如果ID存在则修改(如果添加的数据ID重复/存在,新的数据覆盖原来的数据)
     */
    public static void main(String[] args) throws Exception {
        // 1、创建一个restClient客户端,用于访问ES
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200,"http"); // hostname：本机地址,port：端口号,scheme：HTTP协议
        RestClientBuilder restClientBuilder = RestClient.builder(httpHost); // rest客户端构建器
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder); // rest高级客户端
        // 2、创建一个对应行为的请求对象
        BulkRequest bulkRequest = new BulkRequest();
        IndexRequest indexRequest1 = new IndexRequest("zhaoyu","doc");
        IndexRequest indexRequest2 = new IndexRequest("zhaoyu","doc");
        // 方法一(Map存储)：
        Map map1 = new HashMap();
        map1.put("name","李四");
        map1.put("sex","女");
        map1.put("age",21);
        map1.put("types","赵宇牛逼");
        Map map2 = new HashMap();
        map2.put("name","张三");
        map2.put("sex","男");
        map2.put("age",20);
        map2.put("types","宇尘牛逼");
        indexRequest1.source(map1); // 存入封装后的查询条件/设置查询条件构造器
        indexRequest2.source(map2); // 存入封装后的查询条件/设置查询条件构造器
        bulkRequest.add(indexRequest1);
        bulkRequest.add(indexRequest2);
        // 方法二(直接存储)：
        /* indexRequest1.source("{\n" +
                "\t\"name\": \"宇尘\",\n" +
                "\t\"sex\": \"男\",\n" +
                "\t\"age\": 19,\n" +
                "\t\"types\": \"YYDS\"\n" +
                "}",XContentType.JSON); // 存入封装后的查询条件/设置查询条件构造器
        indexRequest2.source("{\n" +
                "\t\"name\": \"赵宇\",\n" +
                "\t\"sex\": \"男\",\n" +
                "\t\"age\": 19,\n" +
                "\t\"types\": \"牛逼\"\n" +
                "}",XContentType.JSON); // 存入封装后的查询条件/设置查询条件构造器
        bulkRequest.add(indexRequest1);
        bulkRequest.add(indexRequest2); */
        // 3、触发请求,获取响应结果
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
        // 4、使用响应的结果
        int status = bulkResponse.status().getStatus();
        System.out.println(status);
        // 5、关闭ES客户端
        restHighLevelClient.close();
    }

}